package com.yuan.pdf.controller;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.yuan.pdf.util.ImgUtil;
import com.yuan.pdf.util.PdfKeywordFinder;

import java.io.*;

import static com.yuan.pdf.controller.CreatContract.DEST;

/**
 * 签章测试
 * @author siyuan
 * @date 2023/1/9 13:58
 */
public class AddSignatureToImg {
    /**
     * 添加签章
     */
    public static void main(String[] args) throws IOException, DocumentException {
        //base64字符串,线上通过ResponseBody获取
        String signData = "";
        String oldPdfUrl = DEST + "合同D20230109XiongDa-temp.pdf";
        String newPdfUrl = DEST + "合同D20230109XiongDa.pdf";
        //查找签名位置
        float[] position = PdfKeywordFinder.getAddImagePositionXY(oldPdfUrl, "承租人(乙方)签章：");
        //Read file using PdfReader
        PdfReader pdfReader = new PdfReader(oldPdfUrl);
        System.out.println("x:" + position[1] + " y:" + position[2]);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(newPdfUrl));
        //生成电子签字字节 字节流数组转为图片
        byte[] imgByte = ImgUtil.base64ToImg(signData);
        Image image = Image.getInstance(imgByte);
        //图片缩放
        image.scaleAbsolute(100, 50);
        //绝对位置
        image.setAbsolutePosition(position[1], position[2]);
        //页码数
        System.out.println("pages:" + pdfReader.getNumberOfPages());
        PdfContentByte content = pdfStamper.getUnderContent((int) position[0]);
        content.addImage(image);
        pdfStamper.close();
    }
}
